import { getCurrentInstance } from 'vue';

export function use找组件() {
  const instance = getCurrentInstance();
  // console.log(`instance 👉`, instance)

  function 找父组件(name) {
    let parent = instance.parent;
    while (parent) {
      // console.log(`parent.type.name 👉`, parent.type.name)
      if (parent.type.name !== name) {
        parent = parent.parent;
      } else {
        return parent;
      }
    }
    return null;
  }

  function 找子组件(name) {
    let result = [];
    // console.log(`instance 👉`, instance)
    // let childrens = instance.vnode.children.default();
    let childrens = instance.subTree.children[0].children;
    // console.log(`childrens 👉`, childrens)
    while (childrens && childrens.length > 0) {
      childrens.forEach((child) => {
        // console.log(`child 👉`, child)
        if (child.type.name === name) {
          // console.log(`child 👉`, child)
          result.push(child);
        }
        // In Vue 3, accessing $children is deprecated. Use children instead.
        const childsChildren = child.children;
        // console.log(`childsChildren 👉`, childsChildren)
        if (childsChildren && childsChildren.length > 0) {
          childrens = childsChildren;
        } else {
          childrens = null;
        }
      });
    }

    return result;
  }

  return { 找父组件, 找子组件 };
}
